﻿using System;

using System.Data;
using Epm.AppLogic.Framework;

namespace msBsc.WebUi
{
    public partial class wfSysMenuConfig : msBsc.Cls.BPageHt
    { 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindControls(); 
                //sRadom.Value = GetRadomString();
                this.txtId.Value = GetFormParam("R_ID"); 
            }
            else
            {
                //this.ExecJScript("initVoy();");
            }
        }
        private void BindControls()
        {
            if (!IsPostBack)
            {
                //DataSet dsCons = this.DataConst;
                //BoundComboBox(dplMenuType, dsCons, "CONSTANT_DISP_TEXT", "CONSTANT_VALUE", "(CONSTANT_CATEGORY_CID='BSE_MENU_TYPE_CID')", "SEQ_NUM ASC", true);
                ////PageUtils.BoundComboBox(dplUSER_TYPE_CID, this.DataConst, "CONSTANT_DISP_TEXT", "CONSTANT_VALUE", "CONSTANT_CATEGORY_CID = 'EPM_EXEC_USER_FILTER_TYPE_CID'", "SEQ_NUM ASC", true);
            }
        } 

        //id:1, //ID只能包含英文数字下划线中划线
        //text:"node 1",
        //value:"1",
        //showcheck:false,
        //checkstate:0,         //0,1,2
        //hasChildren:true,
        //isexpand:false,
        //complete:false, 是否已加载子节点
        //ChildNodes:[] // child nodes
        private string GetNodeJson(DataSet dsOfce, DataRow drC)
        {
            if (drC.RowState == DataRowState.Deleted || drC["MENU_CONFIG_ID"].ToString()==string.Empty) return ""; 
            string strNodeJson = "{"; 
            strNodeJson += "\"id\":\"" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(drC["MENU_CONFIG_ID"].ToString()) + "\"";
            strNodeJson += ",\"text\":\"" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(drC["MENU_NAME"].ToString()) + "\"";
            strNodeJson += ",\"value\":\"" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(drC["MENU_CONFIG_ID"].ToString()) + "\"";
            string showcheck = "true"; 
            strNodeJson += ",\"showcheck\":" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(showcheck) + "";
            strNodeJson += ",\"checkstate\":" + msBsc.AppLogic.Cfg.HttpTools.stringToJson("0") + "";
            string strChildJson = GetChildJson(dsOfce, drC["MENU_CONFIG_ID"].ToString());
            string hasChildren = "false";
            if (strChildJson != string.Empty)
            {
                hasChildren = "true";
            }
            strNodeJson += ",\"hasChildren\":" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(hasChildren) + "";
            strNodeJson += ",\"isexpand\":" + msBsc.AppLogic.Cfg.HttpTools.stringToJson("false") + "";
            strNodeJson += ",\"complete\":" + msBsc.AppLogic.Cfg.HttpTools.stringToJson("true") + "";
            strNodeJson += ",\"ChildNodes\":[" + strChildJson + "]";
            strNodeJson += "}";
            return strNodeJson;
        }
        public string GetMenuJson(DataSet dsOfce)
        {
            string strRet = "";
            DataRow[] arrRC = dsOfce.Tables[0].Select("PARENT_MENU_ID IS NULL OR PARENT_MENU_ID = ''");// + wfBase.MenuType() + "'");
            strRet += "{\"data\":[";
            int i = 0; 
            foreach (DataRow drC in arrRC)
            {
                string strNodeJson = GetNodeJson(dsOfce,drC);
                if (strNodeJson == string.Empty)
                    continue;
                if (i != 0)
                    strNodeJson = "," + strNodeJson; 
                strRet += strNodeJson;
                i++;
            }
            strRet += "]}";

            return strRet;
        }
        private string GetChildJson(DataSet dsOfce, string pNodeId)
        {
            DataRow[] arrRC = dsOfce.Tables[0].Select("PARENT_MENU_ID = '" + pNodeId + "'");
            int i = 0;
            string strRet = "";
            foreach (DataRow drC in arrRC)
            {
                string strNodeJson = GetNodeJson(dsOfce, drC);
                if (strNodeJson == string.Empty)
                    continue;
                if (i != 0)
                    strNodeJson = "," + strNodeJson;
                strRet += strNodeJson;
                i++;
            }

            return strRet;
        }
        //获取数据原,"DP_DATA"字符一定不要改变，否则系统不能自动清除缓存
        public DataSet GetDisplayData(string strgtGridID,  string strsRadom)
        {
            if (strgtGridID == "myGrid1")
            {
                DataSet ds;
                if (!this.SessionIsExists(strsRadom + "DP_DATA", "2"))//点击查询按钮时，或需要数据而没有缓存时，根据条件取出数据记录
                {
                    using (CDbAccess oCDbAccess = new CDbAccess())
                    {
                        string sqlString = " SELECT * FROM SYS_MENU_CONFIG WHERE (MENU_TYPE = '" + GetParamHtValue("MENU_TYPE") + "') ORDER BY MENU_SEQ_ON_LEVEL ASC";
                        ds = oCDbAccess.QueryBySQL(sqlString);
                        ds.Tables[0].TableName = "SYS_MENU_CONFIG";
                        ds.AcceptChanges();
                    }
                    SetSession(strsRadom + "DP_DATA", ds, "2"); 
                }
                else
                {
                    ds = (DataSet)this.GetSession(strsRadom + "DP_DATA", "2");
                }
                return ds;
            } 
            else
            {
                return null;
            }
        }
        private void ShowOfficeTree()
        {
            DataSet dsSrc = GetDisplayData("myGrid1", sCurrPageRadom); 
            this.AddCustJson("Office", GetMenuJson(dsSrc ));
        }
        private void SetMode(string strMode)
        {
            EditMode = strMode;switch (strMode)
            {
                case "EDIT":
                    EnabledLinkBtn("btnTJNew", false);
                    EnabledLinkBtn("btnZJNew", false);
                    EnabledLinkBtn("btnEdit", false);
                    EnabledLinkBtn("btnSave", true);
                    EnabledLinkBtn("btnDelete", true);

                    SetPanalEditMode("divOfficeDetail", "EDIT");

                    break;
                case "ADD":
                    EnabledLinkBtn("btnTJNew", false);
                    EnabledLinkBtn("btnZJNew", false);
                    EnabledLinkBtn("btnEdit", false);
                    EnabledLinkBtn("btnSave", true);
                    EnabledLinkBtn("btnDelete", false);
                    SetPanalEditMode("divOfficeDetail", "ADD");
                    SetDefalutValueToAdd();
                    break;
                case "VIEW":
                    EnabledLinkBtn("btnTJNew", true);
                    EnabledLinkBtn("btnZJNew", true);
                    if (this.GetParamHtValue("ID") != string.Empty)
                        EnabledLinkBtn("btnEdit", true);
                    else
                        EnabledLinkBtn("btnEdit", false);
                    EnabledLinkBtn("btnSave", false);
                    EnabledLinkBtn("btnDelete", true);

                    SetPanalEditMode("divOfficeDetail", "VIEW");
                    break;
            }
        }
        //设置新增时的默认值
        private void SetDefalutValueToAdd()
        {
            this.ExecJScript("SetCEmpty('divOfficeDetail');");
            string strId = this.GetParamHtValue("ID");
            string strMsg = "当前新增菜单的上级菜单为空!";
            if (strId != string.Empty)
            {
                using (CDbAccess oCDbAccess = new CDbAccess())
                {
                    DataSet ds = oCDbAccess.QueryBySQL("SELECT * FROM SYS_MENU_CONFIG WHERE MENU_CONFIG_ID='"+strId+"'");
                    if (this.GetParamHtValue("sAddType") == "btnTJNew")
                    {
                        strMsg = "当前新增菜单为【" + ds.Tables[0].Rows[0]["MENU_NAME"].ToString() + "】的同级菜单!";
                    }
                    else
                    {
                        strMsg = "当前新增菜单为【" + ds.Tables[0].Rows[0]["MENU_NAME"].ToString() + "】的子级菜单!";
                    }
                }
            }
            this.SetContrlValue("txtOperate", strMsg);
        }
        private string SaveData()
        {
            if (GetParamHtValue("MENU_TYPE") == string.Empty)
            {
                throw new Exception("请先选择菜单类型！"); 
            }
            string strId = this.GetParamHtValue("ID");
            DataSet dsSrc = GetDisplayData("myGrid1", sCurrPageRadom);
            DataRow[] arrtem1 = dsSrc.Tables[0].Select("MENU_CONFIG_ID='" + strId+"'"); 
            DataRow drNew;
            bool blAdd = false;
            if (this.GetParamHtValue("sAddType") == "btnTJNew")
            {
                drNew = dsSrc.Tables[0].NewRow();
                drNew["PARENT_MENU_ID"] = "";
                drNew["MENU_CONFIG_ID"] = "";
                drNew["MENU_TYPE"] = GetParamHtValue("MENU_TYPE");
                if (GetPostHtValue("PARENT_MENU_ID") == string.Empty && arrtem1.Length > 0)
                {
                    drNew["PARENT_MENU_ID"] = arrtem1[0]["PARENT_MENU_ID"];
                }
                else
                {
                    drNew["PARENT_MENU_ID"] = GetPostHtValue("PARENT_MENU_ID");
                }
                dsSrc.Tables[0].Rows.Add(drNew);
                blAdd = true;
            }
            else if (this.GetParamHtValue("sAddType") == "btnZJNew")
            {
                drNew = dsSrc.Tables[0].NewRow();
                drNew["PARENT_MENU_ID"] = "";
                drNew["MENU_CONFIG_ID"] = "";
                drNew["MENU_TYPE"] = GetParamHtValue("MENU_TYPE");
                if (GetPostHtValue("PARENT_MENU_ID") == string.Empty && arrtem1.Length > 0)
                {
                    drNew["PARENT_MENU_ID"] = strId;
                }
                else
                {
                    drNew["PARENT_MENU_ID"] = GetPostHtValue("PARENT_MENU_ID");
                }
                dsSrc.Tables[0].Rows.Add(drNew);
                blAdd = true;
            }
            else
            {
                if (arrtem1.Length > 0)
                {
                    drNew = arrtem1[0];
                    drNew["PARENT_MENU_ID"] = GetPostHtValue("PARENT_MENU_ID");
                }
                else
                {
                    return  "";
                }
            }
            msBsc.AppLogic.Cfg.HttpTools.SetDataValueByHashtableValue(this.htPostDataRow, drNew, "PARENT_MENU_ID");
            //this.SetContrlValue("txtOperate", strMsg); 
            System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
            transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            transactionOption.Timeout = new TimeSpan(0, 10, 0);
            using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
            {
                if (dsSrc.HasChanges())
                {
                    using (CustBizObject oBizObject = new CustBizObject(dsSrc.Tables[0], "SYS_MENU_CONFIG", "MENU_CONFIG_ID"))
                    {
                        oBizObject.Update(dsSrc );
                        dsSrc.AcceptChanges();
                    }
                }
                ts.Complete();
                ts.Dispose();
            }
            if (blAdd)
            {
                ShowOfficeTree();
                this.SetContrlValue("txtId", drNew["MENU_CONFIG_ID"].ToString());
            }
            return "OK";
        }
         

        private void Remove()
        {
            string strSELECTED_IDS = GetParamHtValue("SELECTED_IDS");
            DataSet dsSrc = GetDisplayData("myGrid1", sCurrPageRadom);
            DataRow[] arrtem1 = dsSrc.Tables[0].Select("MENU_CONFIG_ID IN ('" + strSELECTED_IDS.Replace(",","','") + "')");
            for (int i = arrtem1.Length - 1; i >= 0; i--)
            {
                arrtem1[i].Delete();
            }
            System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
            //设置事务隔离级别
            transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            // 设置事务超时时间为60秒
            transactionOption.Timeout = new TimeSpan(0, 10, 0);
            using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
            {
                if (dsSrc.HasChanges())
                {
                    using (CustBizObject oBizObject = new CustBizObject(dsSrc.Tables[0], "SYS_MENU_CONFIG", "MENU_CONFIG_ID"))
                    {
                        oBizObject.Update(dsSrc );
                    }
                }
                ts.Complete();
                ts.Dispose();
                ShowOfficeTree();
                this.SetContrlValue("txtId", "");
                this.ExecJScript("SetCEmpty('divOfficeDetail');"); 

                this.Alert("已成功删除数据！"); 
                //如果有子表，在中间层的主表数据删除时要做删除子表处理。
            }
        }
        //显示数据
        private void ShowData(string strId)
        {
            try
            {
                if (strId != "")
                {
                    using (CDbAccess oCDbAccess = new CDbAccess())
                    {
                        DataSet dsMaster = oCDbAccess.QueryBySQL("SELECT * FROM SYS_MENU_CONFIG WHERE MENU_CONFIG_ID='" + strId + "'");
                        //DataSet dsMaster = this.objSysMenuConfig.SelectById(strId);

                        if (dsMaster.Tables[0].Rows.Count <= 0)
                        {
                            this.Alert("信息未找到！");
                            return;
                        }
                        else
                        {
                            this.AddPageRetRow("divOfficeDetail", dsMaster.Tables[0].Rows[0]);
                        }
                    }
                }
            }
            catch (Exception err)
            {
                this.Alert("服务器端错误："+err.Message);
            }

        }

        public override void InitialByParam()
        {
            if (strAction == "mShowOfficeTree")
            {
                SetSession(sCurrPageRadom + "DP_DATA",null,"2");
                ShowOfficeTree();
                SetMode("VIEW"); 
            }
            else if (strAction == "mShowDetail")
            {
                ShowData(this.GetParamHtValue("ID"));
                SetMode("VIEW");
                this.SetContrlValue("sAddType", "");
                this.SetContrlValue("txtOperate", "");
            }
            else if (strAction == "btnTJNew" || strAction == "btnZJNew")
            {
                string strId = this.GetParamHtValue("ID");
                if (strAction == "btnTJNew")
                {
                    DataSet dsSrc = GetDisplayData("myGrid1", sCurrPageRadom);
                    DataRow[] arrtem1 = dsSrc.Tables[0].Select("MENU_CONFIG_ID='" + strId + "'");  
                    if (arrtem1.Length > 0)
                    {
                        SetContrlValue("txtPARENT_MENU_ID", arrtem1[0]["PARENT_MENU_ID"].ToString());  
                    } 
                }
                else if (strAction == "btnZJNew")
                {
                    SetContrlValue("txtPARENT_MENU_ID", strId); 
                }
                SetMode("ADD"); 
            }
            else if (strAction == "btnEdit")
            {
                SetMode("EDIT");
                this.SetContrlValue("sAddType", "");
                this.SetContrlValue("txtOperate", "");
                ShowOfficeTree( );
            }
            else if (strAction == "btnSave")
            {
                SaveData();
                SetMode("VIEW");
                this.SetContrlValue("sAddType", "");
                this.SetContrlValue("txtOperate", "");
            }
            else if (strAction == "btnDelete")
            {
                Remove();
                SetMode("VIEW");
                this.SetContrlValue("sAddType", "");
                this.SetContrlValue("txtOperate", "");
            }

            base.InitialByParam();
        } 

    }
}
